package com.jwsoft.manager.core.integration.dataStatistics.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.engine.protect.core.annotation.NoSignCrypto;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.ExcelModelVO;
import com.bifang.module.base.common.vo.excel.ExcelVO;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.system.core.integration.impl.ExcelIntegrationImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.SchoolCategoryEnum;
import com.jwsoft.manager.common.enums.SchoolDictEnum;
import com.jwsoft.manager.common.vo.dataStatistics.school.SchoolEnrollCntVO;
import com.jwsoft.manager.common.vo.dataStatistics.school.SchoolEnrollQueryVO;
import com.jwsoft.manager.common.vo.dataStatistics.school.SchoolEnrollVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolQueryVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.core.dao.model.EduArea;
import com.jwsoft.manager.core.dao.service.EduAreaService;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.EduSchoolService;
import com.jwsoft.manager.core.dao.service.EduhStudentEnrollService;
import com.jwsoft.manager.core.integration.dataStatistics.SchoolDataIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@ApiService(funcCode = "schoolData", title = "学校相关数据统计")
@Slf4j
public class SchoolDataIntegrationImpl implements SchoolDataIntegration {
    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private EduAreaService eduAreaService;
    @Autowired
    private DictHelper dictHelper;
    @Autowired
    public ExcelIntegrationImpl excelIntegration;
    @Value("${spring.servlet.multipart.location}")
    private String tempPath;
    @Autowired
    ExcelCommonHelper excelCommonHelper;
    @Autowired
    DictIntegration dictIntegration;

    @Autowired
    private EduDataTaskDetailService eduDataTaskDetailService;

    @Autowired
    public EduhStudentEnrollService eduhStudentEnrollService;

    @Autowired
    private static final String STUDENT_ENROLL_TABLE = "edu_student_enroll";

    public static final String handleTable = "edu_student_status";


    @Override
    @OpApi(funcCode = "schoolData0001", title = "获取义务段学校报名情况统计信息", funcType = FuncTypeEnum.query)
    public PageInfo<SchoolEnrollVO> getYwRegistStatistics(SchoolEnrollQueryVO vo) {
        PageInfo<SchoolEnrollVO> pageInfo = queryYwRegistStatistics(Convert.convert(EduSchoolQueryVO.class, vo));
        return pageInfo;
    }

    @Override
    @OpApi(funcCode = "schoolData0002", title = "获取幼儿园报名统计信息", funcType = FuncTypeEnum.query)
    public PageInfo<SchoolEnrollVO> getYeyRegistStatistics(SchoolEnrollQueryVO vo) {
        PageInfo<SchoolEnrollVO> pageInfo = queryYeyRegistStatistics(Convert.convert(EduSchoolQueryVO.class, vo));
        return pageInfo;
    }

    @Override
    @OpApi(funcCode = "schoolData0003", title = "学校数据统计信息导出", funcType = FuncTypeEnum.other)
    @NoSignCrypto
    public void downloadData(SchoolEnrollQueryVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO = excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum = 1;
        setData(excelModelVO, null, destFilePath, vo, pageNum);
        String fileName = vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }
    }

    @Override
    @OpApi(funcCode = "schoolData0004", title = "义务段按类别统计报名数据", funcType = FuncTypeEnum.query)
    public PageInfo<SchoolEnrollVO> getYwRegistStatisticsLb(SchoolEnrollQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(50);
        }
        if (ObjectUtils.isEmpty(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        if ("1".equalsIgnoreCase(vo.getIsbqFlag())) {
            vo.setBbFlag(BoolEnum.TRUE.getType());
        } else if ("2".equalsIgnoreCase(vo.getIsbqFlag())) {
            vo.setSpareRegisterFlag(BoolEnum.TRUE.getType());
        }
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<SchoolEnrollVO> schoolVOList;
        //判断是否迁移过
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),STUDENT_ENROLL_TABLE);
        if (!queryHistoryFlag) {
             schoolVOList = eduSchoolService.queryBmByLb(vo);
        }else {
            //迁移过就判断查询条件是否加密
            Boolean encryptFlag = eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), STUDENT_ENROLL_TABLE);
            if (encryptFlag) {
            }
            schoolVOList = eduSchoolService.queryBmByLbHistory(vo);
        }
        if (CollectionUtils.isEmpty(schoolVOList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        PageInfo<SchoolEnrollVO> pageInfo = new PageInfo<>(schoolVOList);
        List<String> streetList = schoolVOList.stream().map(SchoolEnrollVO::getStreet).distinct().collect(Collectors.toList());
        QueryWrapper<EduArea> areaQueryWrapper = new QueryWrapper<>();
        areaQueryWrapper.lambda().in(EduArea::getLocalCode, streetList);
        List<EduArea> areaList =
                eduAreaService.list(areaQueryWrapper);

        Map<String, String> streetMap = areaList.stream().collect(Collectors.toMap(EduArea::getLocalCode, EduArea::getAreaName));
        for (SchoolEnrollVO eduSchoolVO : pageInfo.getList()) {
            if (!ObjectUtils.isEmpty(eduSchoolVO.getStreet())) {
                eduSchoolVO.setStreetName(streetMap.get(eduSchoolVO.getStreet()));
            }
            if (!ObjectUtils.isEmpty(eduSchoolVO.getAreaCode())) {
                eduSchoolVO.setAreaName(dictHelper.getAreaNameByCode(eduSchoolVO.getAreaCode()));
            }
        }
        dictHelper.valueToName(pageInfo.getList(), Arrays.asList(SchoolDictEnum.values()));
        return pageInfo;
    }

    private PageInfo<SchoolEnrollVO> queryYwRegistStatistics(EduSchoolQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(50);
        }
        if (ObjectUtils.isEmpty(vo.getAreaCode())) {
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        Map<String, Object> queryMap = BeanUtil.beanToMap(vo, false, true);
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<SchoolEnrollVO> schoolVOList = eduSchoolService.queryRegistStatistics(queryMap);
        if (CollectionUtils.isEmpty(schoolVOList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        PageInfo<SchoolEnrollVO> pageInfo = new PageInfo<>(schoolVOList);
        List<String> streetList = schoolVOList.stream().map(SchoolEnrollVO::getStreet).distinct().collect(Collectors.toList());
        QueryWrapper<EduArea> areaQueryWrapper = new QueryWrapper<>();
        areaQueryWrapper.lambda().in(EduArea::getLocalCode, streetList);
        List<EduArea> areaList =
                eduAreaService.list(areaQueryWrapper);

        Map<String, String> streetMap = areaList.stream().collect(Collectors.toMap(EduArea::getLocalCode, EduArea::getAreaName));


        List<String> schoolIdList = pageInfo.getList().stream().map(SchoolEnrollVO::getOrgId).distinct().collect(Collectors.toList());
        SchoolEnrollQueryVO schoolEnrollQueryVO = Convert.convert(SchoolEnrollQueryVO.class, vo);
        schoolEnrollQueryVO.setSchoolIdList(schoolIdList);
        List<SchoolEnrollCntVO> applyNumList;
        List<SchoolEnrollCntVO> applyYxNumList;
        List<SchoolEnrollCntVO> auditWaitNumList;
        List<SchoolEnrollCntVO> auditNumList;
        List<SchoolEnrollCntVO> admitNumList;
        List<SchoolEnrollCntVO> admitXxNumList;
        List<SchoolEnrollCntVO> fromNumList;
        List<SchoolEnrollCntVO> toNumList;
        List<SchoolEnrollCntVO> sqNumList;
        List<SchoolEnrollCntVO> fsqNumList;
        List<SchoolEnrollCntVO> tstdNumList;
        List<SchoolEnrollCntVO> bbNumList;
        List<SchoolEnrollCntVO> qbNumList;
        //根据任务判断是否当前年度处理过迁移数据
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),STUDENT_ENROLL_TABLE);
        if (!queryHistoryFlag) {
            //报名总人数map
            applyNumList = eduSchoolService.queryApplyNum(schoolEnrollQueryVO);
            //有效报名人数map
            applyYxNumList = eduSchoolService.queryApplyYxNum(schoolEnrollQueryVO);
            //待审核人数
            auditWaitNumList = eduSchoolService.queryAuditWaitNum(schoolEnrollQueryVO);
            //待录取
            auditNumList = eduSchoolService.queryAuditNum(schoolEnrollQueryVO);
            //已录取
            admitNumList = eduSchoolService.queryAdmitNum(schoolEnrollQueryVO);
            //已录取 学校录入人数
            admitXxNumList = eduSchoolService.queryAdmitXxNum(schoolEnrollQueryVO);
            //调出人数map
            fromNumList = eduSchoolService.queryFromNum(schoolEnrollQueryVO);
            //调入人数map
            toNumList = eduSchoolService.queryToNum(schoolEnrollQueryVO);
            //随迁人数
            sqNumList = eduSchoolService.querySqNum(schoolEnrollQueryVO);
            //非随迁人数
            fsqNumList = eduSchoolService.queryFsqNum(schoolEnrollQueryVO);
            //特殊通道人数
            tstdNumList = eduSchoolService.queryTstdNum(schoolEnrollQueryVO);
            //补报人数
            bbNumList = eduSchoolService.queryBbNum(schoolEnrollQueryVO);
            //抢报人数
            qbNumList = eduSchoolService.queryQbNum(schoolEnrollQueryVO);
        }else {
            //报名总人数map
            applyNumList = eduSchoolService.queryApplyNumHistory(schoolEnrollQueryVO);
            //有效报名人数map
            applyYxNumList = eduSchoolService.queryApplyYxNumHistory(schoolEnrollQueryVO);
            //待审核人数
            auditWaitNumList = eduSchoolService.queryAuditWaitNumHistory(schoolEnrollQueryVO);
            //待录取
            auditNumList = eduSchoolService.queryAuditNumHistory(schoolEnrollQueryVO);
            //已录取
            admitNumList = eduSchoolService.queryAdmitNumHistory(schoolEnrollQueryVO);
            //已录取 学校录入人数
            admitXxNumList = eduSchoolService.queryAdmitXxNumHistory(schoolEnrollQueryVO);
            //调出人数map
            fromNumList = eduSchoolService.queryFromNumHistory(schoolEnrollQueryVO);
            //调入人数map
            toNumList = eduSchoolService.queryToNumHistory(schoolEnrollQueryVO);
            //随迁人数
            sqNumList = eduSchoolService.querySqNumHistory(schoolEnrollQueryVO);
            //非随迁人数
            fsqNumList = eduSchoolService.queryFsqNumHistory(schoolEnrollQueryVO);
            //特殊通道人数
            tstdNumList = eduSchoolService.queryTstdNumHistory(schoolEnrollQueryVO);
            //补报人数
            bbNumList = eduSchoolService.queryBbNumHistory(schoolEnrollQueryVO);
            //抢报人数
            qbNumList = eduSchoolService.queryQbNumHistory(schoolEnrollQueryVO);
        }
        Map<String, Long> applyNumMap = getCntMap(applyNumList);
        Map<String, Long> applyYxNumMap = getCntMap(applyYxNumList);
        Map<String, Long> auditWaitNumMap = getCntMap(auditWaitNumList);
        Map<String, Long> auditNumMap = getCntMap(auditNumList);
        Map<String, Long> admitNumMap = getCntMap(admitNumList);
        Map<String, Long> admitXxNumMap = getCntMap(admitXxNumList);
        Map<String, Long> fromNumMap = getCntMap(fromNumList);
        Map<String, Long> toNumMap = getCntMap(toNumList);
        Map<String, Long> sqNumMap = getCntMap(sqNumList);
        Map<String, Long> fsqNumMap = getCntMap(fsqNumList);
        Map<String, Long> tstdNumMap = getCntMap(tstdNumList);
        Map<String, Long> bbNumMap = getCntMap(bbNumList);
        Map<String, Long> qbNumMap = getCntMap(qbNumList);
        for (SchoolEnrollVO eduSchoolVO : pageInfo.getList()) {
            if (!ObjectUtils.isEmpty(eduSchoolVO.getStreet())) {
                eduSchoolVO.setStreetName(streetMap.get(eduSchoolVO.getStreet()));
            }
            if (!ObjectUtils.isEmpty(eduSchoolVO.getAreaCode())) {
                eduSchoolVO.setAreaName(dictHelper.getAreaNameByCode(eduSchoolVO.getAreaCode()));
            }
            String key = eduSchoolVO.getOrgId() + eduSchoolVO.getConfigTypeName();
            eduSchoolVO.setApplyNum(0L);
            eduSchoolVO.setApplyYxNum(0L);
            eduSchoolVO.setAuditWaitNum(0L);
            eduSchoolVO.setAuditNum(0L);
            eduSchoolVO.setAdmitNum(0L);
            eduSchoolVO.setAdmitXxNum(0L);
            eduSchoolVO.setFromNum(0L);
            eduSchoolVO.setToNum(0L);
            eduSchoolVO.setLqSqNum(0L);
            eduSchoolVO.setLqFsqNum(0L);
            eduSchoolVO.setLqTstdNum(0L);
            eduSchoolVO.setLqBbNum(0L);
            eduSchoolVO.setLqQbNum(0L);
            if (!ObjectUtils.isEmpty(applyNumMap.get(key))) {
                if (!ObjectUtils.isEmpty(fromNumMap.get(key))) {
                    //调出人数
                    eduSchoolVO.setFromNum(fromNumMap.get(key));
                }
                //报名总人数
                eduSchoolVO.setApplyNum(applyNumMap.get(key) + eduSchoolVO.getFromNum());
                if (!ObjectUtils.isEmpty(applyYxNumMap.get(key))) {
                    //有效报名总人数
                    eduSchoolVO.setApplyYxNum(applyYxNumMap.get(key) + eduSchoolVO.getFromNum());
                    if (!ObjectUtils.isEmpty(auditWaitNumMap.get(key))) {
                        //待审核人数
                        eduSchoolVO.setAuditWaitNum(auditWaitNumMap.get(key));
                    }
                    if (!ObjectUtils.isEmpty(auditNumMap.get(key))) {
                        //待录取人数
                        eduSchoolVO.setAuditNum(auditNumMap.get(key));
                    }
                    if (!ObjectUtils.isEmpty(admitNumMap.get(key))) {
                        //录取人数
                        eduSchoolVO.setAdmitNum(admitNumMap.get(key));
                        if (!ObjectUtils.isEmpty(toNumMap.get(key))) {
                            //调入人数
                            eduSchoolVO.setToNum(toNumMap.get(key));
                        }
                        if (!ObjectUtils.isEmpty(admitXxNumMap.get(key))) {
                            //学校录入人数
                            eduSchoolVO.setAdmitXxNum(admitXxNumMap.get(key));
                        }
                        if (!ObjectUtils.isEmpty(sqNumMap.get(key))) {
                            //随迁人数
                            eduSchoolVO.setLqSqNum(sqNumMap.get(key));
                        }
                        if (!ObjectUtils.isEmpty(fsqNumMap.get(key))) {
                            //非随迁人数
                            eduSchoolVO.setLqFsqNum(fsqNumMap.get(key));
                        }
                        if (!ObjectUtils.isEmpty(tstdNumMap.get(key))) {
                            //特殊通道
                            eduSchoolVO.setLqTstdNum(tstdNumMap.get(key));
                        }
                        if (!ObjectUtils.isEmpty(bbNumMap.get(key))) {
                            //补报人数
                            eduSchoolVO.setLqBbNum(bbNumMap.get(key));
                        }
                        if (!ObjectUtils.isEmpty(qbNumMap.get(key))) {
                            //抢报人数
                            eduSchoolVO.setLqQbNum(qbNumMap.get(key));
                        }

                    }

                }
            }


        }
        // 转义数据字典值
        dictHelper.valueToName(pageInfo.getList(), Arrays.asList(SchoolDictEnum.values()));
        return pageInfo;
    }

    private PageInfo<SchoolEnrollVO> queryYeyRegistStatistics(EduSchoolQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(50);
        }
        Map<String, Object> queryMap = BeanUtil.beanToMap(vo, false, true);
        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (!CollectionUtils.isEmpty(areaCodeList)){
            queryMap.put("areaCodeList",areaCodeList);
        }else{
            throw new AppException("必须传入行政区划");
        }
        if (vo.getYear() == null) {
            vo.setYear(eduHelper.thisYear());
        }
        vo.setSchoolCategory(SchoolCategoryEnum.KINDERGARTEN.getType());
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<SchoolEnrollVO> schoolVOList = eduSchoolService.queryRegistStatistics(queryMap);
        if (CollectionUtils.isEmpty(schoolVOList)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        PageInfo<SchoolEnrollVO> pageInfo = new PageInfo<>(schoolVOList);
        List<String> streetList = schoolVOList.stream().map(SchoolEnrollVO::getStreet).distinct().collect(Collectors.toList());
        QueryWrapper<EduArea> areaQueryWrapper = new QueryWrapper<>();
        areaQueryWrapper.lambda().in(EduArea::getLocalCode, streetList);
        List<EduArea> areaList =
                eduAreaService.list(areaQueryWrapper);

        Map<String, String> streetMap = areaList.stream().collect(Collectors.toMap(EduArea::getLocalCode, EduArea::getAreaName));
        List<String> schoolIdList = pageInfo.getList().stream().map(SchoolEnrollVO::getOrgId).distinct().collect(Collectors.toList());
        SchoolEnrollQueryVO schoolEnrollQueryVO = Convert.convert(SchoolEnrollQueryVO.class, vo);
        schoolEnrollQueryVO.setSchoolIdList(schoolIdList);
        //根据任务判断是否当前年度处理过迁移数据
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),handleTable);
        List<SchoolEnrollCntVO> applyNumList;
        List<SchoolEnrollCntVO> auditWaitNumList;
        List<SchoolEnrollCntVO> auditNumList;
        List<SchoolEnrollCntVO> admitNumList;
        if (!queryHistoryFlag) {
            //招生报名人数map
             applyNumList = eduSchoolService.queryYeyApplyNum(schoolEnrollQueryVO);
            //待审核
             auditWaitNumList = eduSchoolService.queryYeyAuditWaitNum(schoolEnrollQueryVO);
            //待录取
            auditNumList = eduSchoolService.queryYeyAuditNum(schoolEnrollQueryVO);
            //录取人数map
            admitNumList = eduSchoolService.queryYeyAdmitNum(schoolEnrollQueryVO);
        }else {
            //招生报名人数map
            applyNumList = eduSchoolService.queryYeyApplyNumHistory(schoolEnrollQueryVO);
            //待审核
            auditWaitNumList = eduSchoolService.queryYeyAuditWaitNumHistory(schoolEnrollQueryVO);
            //待录取
            auditNumList = eduSchoolService.queryYeyAuditNumHistory(schoolEnrollQueryVO);
            //录取人数map
            admitNumList = eduSchoolService.queryYeyAdmitNumHistory(schoolEnrollQueryVO);
        }
        Map<String, Long> applyNumMap = getCntYeyMap(applyNumList);
        Map<String, Long> auditWaitNumMap = getCntYeyMap(auditWaitNumList);
        Map<String, Long> auditNumMap = getCntYeyMap(auditNumList);
        Map<String, Long> admitNumMap = getCntYeyMap(admitNumList);

        for (SchoolEnrollVO eduSchoolVO : pageInfo.getList()) {
            if (!ObjectUtils.isEmpty(eduSchoolVO.getStreet())) {
                eduSchoolVO.setStreetName(streetMap.get(eduSchoolVO.getStreet()));
            }
            if (!ObjectUtils.isEmpty(eduSchoolVO.getAreaCode())) {
                eduSchoolVO.setAreaName(dictHelper.getAreaNameByCode(eduSchoolVO.getAreaCode()));
            }
            String key = eduSchoolVO.getOrgId() + eduSchoolVO.getConfigType();
            eduSchoolVO.setApplyNum(0L);
            eduSchoolVO.setApplyYxNum(0L);
            eduSchoolVO.setAuditWaitNum(0L);
            eduSchoolVO.setAuditNum(0L);
            eduSchoolVO.setAdmitNum(0L);
            eduSchoolVO.setAdmitXxNum(0L);
            eduSchoolVO.setFromNum(0L);
            eduSchoolVO.setToNum(0L);
            if ("1".equalsIgnoreCase(eduSchoolVO.getConfigType())) {
                eduSchoolVO.setConfigTypeName("托班");
            } else if ("2".equalsIgnoreCase(eduSchoolVO.getConfigType())) {
                eduSchoolVO.setConfigTypeName("小班");
            } else if ("3".equalsIgnoreCase(eduSchoolVO.getConfigType())) {
                eduSchoolVO.setConfigTypeName("中班");
            } else if ("4".equalsIgnoreCase(eduSchoolVO.getConfigType())) {
                eduSchoolVO.setConfigTypeName("大班");
            } else if ("5".equalsIgnoreCase(eduSchoolVO.getConfigType())) {
                eduSchoolVO.setConfigTypeName("混龄班");
            }
            if (!ObjectUtils.isEmpty(applyNumMap.get(key))) {
                eduSchoolVO.setApplyNum(applyNumMap.get(key));
                if (!ObjectUtils.isEmpty(auditWaitNumMap.get(key))) {
                    eduSchoolVO.setAuditWaitNum(auditWaitNumMap.get(key));
                }
                if (!ObjectUtils.isEmpty(auditNumMap.get(key))) {
                    eduSchoolVO.setAuditNum(auditNumMap.get(key));
                }
                if (!ObjectUtils.isEmpty(admitNumMap.get(key))) {
                    eduSchoolVO.setAdmitNum(admitNumMap.get(key));
                }
            }

        }
        // 转义数据字典值
        dictHelper.valueToName(pageInfo.getList(), Arrays.asList(SchoolDictEnum.values()));
        return pageInfo;
    }

    //义务段
    private Map<String, Long> getCntMap(List<SchoolEnrollCntVO> list) {
        Map<String, Long> map = new HashMap<>();
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (SchoolEnrollCntVO cntVO : list) {
            map.put(cntVO.getSchoolId() + cntVO.getConfigTypeName(), cntVO.getCnt());
        }
        return map;
    }

    //幼儿园
    private Map<String, Long> getCntYeyMap(List<SchoolEnrollCntVO> list) {
        Map<String, Long> map = new HashMap<>();
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (SchoolEnrollCntVO cntVO : list) {
            map.put(cntVO.getSchoolId() + cntVO.getConfigType(), cntVO.getCnt());
        }
        return map;
    }

    private void setData(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, SchoolEnrollQueryVO vo, int pageNum) {
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag = false;
        try {
            PageInfo<SchoolEnrollVO> pageInfo;
            if (vo.getModelCode().equals("yeySchoolEnrollInfo")) {
                pageInfo = getYeyRegistStatistics(vo);
            } else if (vo.getModelCode().equals("ywSchoolEnrollInfo")) {
                pageInfo = getYwRegistStatistics(vo);
            } else if (vo.getModelCode().equals("ywSchoolEnrollLbInfo")) {
                pageInfo = getYwRegistStatisticsLb(vo);
            } else {
                throw new AppException("导出类型未开发相应功能");
            }
            String total = String.valueOf(pageInfo.getTotal());
            List<Map<String, Object>> list = new ArrayList<>();
            if (!CollectionUtils.isEmpty(pageInfo.getList())) {
                for (SchoolEnrollVO eduSchoolVO : pageInfo.getList()) {
                    list.add(BeanUtil.beanToMap(eduSchoolVO, false, true));
                }
            }
            if (pageNum == 1) {
                if (excelWriter == null) {
                    excelWriter = excelCommonHelper.createExcelWriter(excelModelVO, destFilePath, Integer.parseInt(total));
                }
                excelCommonHelper.writeMap(excelWriter, list);
            } else {
                excelCommonHelper.writeMap(excelWriter, list);
            }
            if (pageInfo.isHasNextPage()) {
                pageNum = pageNum + 1;
                setData(excelModelVO, excelWriter, destFilePath, vo, pageNum);
            } else {
                closeFlag = true;
            }
        } catch (AppException appEx) {
            throw appEx;
        } catch (Exception e) {
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        } finally {
            if (closeFlag && excelWriter != null) {
                excelWriter.close();
            }
        }
    }
}
